package com.matchmaking.system.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.matchmaking.system.config.R;
import com.matchmaking.system.domain.SysMenu;
import com.matchmaking.system.domain.vo.SysMenuEchartsVo;
import com.matchmaking.system.service.SysMenuService;
import com.matchmaking.system.utils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.springframework.http.HttpHeaders.CONTENT_TYPE;

@RestController
@RequestMapping("sysmenu")
public class SysMenuController {


    @Autowired
    SysMenuService sysMenuService;

    /**
     * 获取菜单列表
     *
     * @param sysMenu 条件查询
     * @return 返回值   树形结构的数据
     */
    @PostMapping("list")
    public R list(@RequestBody SysMenu sysMenu) {
        System.err.println("查询方法执行");
        List<SysMenu> list = sysMenuService.list(sysMenu);
        //转换成树形结构
        //转换器
        if (sysMenu.getMenuName() == null || sysMenu.getMenuName() == "") {
            List<Tree<String>> build = TreeUtil.build(list, "0",
                    (treeNode, tree) -> {
                        tree.setId(treeNode.getMenuId() + "");
                        tree.setParentId(treeNode.getParentId() + "");
                        tree.put("menuId", treeNode.getMenuId());
                        tree.put("menuName", treeNode.getMenuName());
                        tree.put("path", treeNode.getPath());
                        tree.put("component", treeNode.getComponent());
                        tree.put("orderNum", treeNode.getOrderNum());
                        tree.put("visible", treeNode.getVisible());
                        tree.put("statuss", treeNode.isStatuss());
                        tree.put("perms", treeNode.getPerms());
                        tree.put("icon", treeNode.getIcon());
                        tree.put("query", treeNode.getQuery());
                        tree.put("isCache", treeNode.getIsCache());
                        tree.put("menuType", treeNode.getMenuType());
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        tree.put("createTime", simpleDateFormat.format(treeNode.getCreateTime()));
                    });
            return R.successed(build);
        }
        return R.successed(list);

    }

    /**
     * 根据id修改目标菜单的使用状态
     *
     * @param id      菜单的id
     * @param statuss 修改后的状态
     * @return 判断信息
     */
    @PutMapping("updateStatus")
    public R updateStatusById(Long id, boolean statuss) {
        System.err.println("根据id修改使用状态方法执行");
        //判断以该id为父菜单的菜单是否有未被禁用的
        //禁用菜单的时候执行，statuss为false
        if (!statuss) {
            boolean b = getSonMenu(id);
            if (b) {
                return R.failed("存在未禁用的子菜单");
            }
        }
        if (statuss) {
            //statuss的值是true，修改对应状态为0
            sysMenuService.updateStatusById(id, 0);
        } else {
            //statuss的值是true，修改对应状态为1
            sysMenuService.updateStatusById(id, 1);
        }

        return R.successed();
    }

    /**
     * 根据父id查询列表中是否有未被禁用的
     *
     * @param id 父id
     * @return 有未被禁用的，返回true  否则返回false
     */
    public boolean getSonMenu(Long id) {
        List<SysMenu> list = sysMenuService.getSonMenu(id);
        for (SysMenu sysMenu : list) {
            if (sysMenu.getStatus().equals("0")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取只有名字和id的树形菜单
     *
     * @return 只有名字和id的树形菜单
     */
    @GetMapping("getParentMenu")
    public R getParentMenu() {
        List<SysMenu> list = sysMenuService.getParentMenu();
        //转换成树形结构
        //转换器
        List<Tree<String>> build = TreeUtil.build(list, "0",
                (treeNode, tree) -> {
                    tree.setId(treeNode.getMenuId() + "");
                    tree.setParentId(treeNode.getParentId() + "");
                    tree.setName(treeNode.getMenuName());
                    tree.put("label", treeNode.getMenuName());
                });

        return R.successed(build);
    }

    @PostMapping("menuAdd")
    @Transactional
    public R menuAdd(@RequestBody SysMenu sysMenu) {

        //根据名称查id
        Long parentId = getIdByName(sysMenu.getParentName());
        sysMenu.setParentId(parentId);
        sysMenu.setCreateTime(new Date());
        System.err.println(sysMenu);
        sysMenuService.insertMenu(sysMenu);
        return R.successed();
    }

    /**
     * 根据名称获取菜单的id
     *
     * @param name 菜单名称
     * @return 菜单id
     */
    public Long getIdByName(String name) {
        Long id = sysMenuService.getIdByName(name);
        return id;
    }

    /**
     * 根据id获取菜单的名称
     *
     * @param parentId
     * @return
     */
    @GetMapping("getNameByParentId")
    public R getNameByParentId(Integer parentId) {
        System.err.println("根据id查名称方法执行");
        String menuName = sysMenuService.getNameByParentId(parentId);
        return R.successed(menuName);
    }

    @PostMapping("menuUpdate")
    public R menuUpdate(@RequestBody SysMenu sysMenu) {
        sysMenu.setUpdateTime(new Date());
        boolean b = sysMenuService.updateById(sysMenu);
        if (b) {
            return R.successed();
        } else {
            return R.failed("修改失败");
        }

    }

    /**
     * 导出excel 包含条件查询
     *
     * @param response
     */
    @RequestMapping("getexcel")
    public void getexcel( HttpServletResponse response){
        System.err.println("导出excel方法执行");
        List<SysMenu> list = sysMenuService.list(null);
        ExcelUtils.exportExcel(list,"菜单导出","菜单",response);
    }

    /**
     * 根据菜单类型统计报表
     * @return 存储报表类型和数量的map集合
     */
    @GetMapping("getechart")
    public R getechart(){
        List<SysMenuEchartsVo> list = sysMenuService.getNumByMenuType();
        return R.successed(list);
    }

    /*
    删除多余菜单
     */
    @DeleteMapping("del")
    public R del(Long id){
        List<SysMenu> list = sysMenuService.getSonMenu(id);
        if (list.isEmpty()){
            sysMenuService.delById(id);
            return R.successed();
        }else {
            return R.failed("存在未删除的子菜单");
        }
    }




}
